#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "newdownloadwindow.h"
#include "downloadtablemodel.h"
#include "delegate.h"
#include <QSqlRecord>
#include <QSqlField>
#include <QTableWidget>
#include <QGridLayout>

MainWindow::MainWindow(QWidget *parent, QSqlDatabase * db) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setMinimumWidth(550);

    table = new QTableView(this);
    tableModel = new DownloadTableModel(this, db);
    table->setModel(tableModel);
    table->setItemDelegate(new Delegate(tableModel));
    table->setAlternatingRowColors(true);

    table->setSortingEnabled(true);
    table->horizontalHeader()->setSortIndicatorShown(true);
    table->horizontalHeader()->setStretchLastSection(true);

    table->setSelectionMode(QTableView::SingleSelection);
    table->setSelectionBehavior(QTableView::SelectRows);

    table->resizeColumnsToContents();
    table->verticalHeader()->hide();
    setCentralWidget(table);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addDownload()
{
    static QSqlQuery query("SELECT * FROM folder");

    query.exec();
    query.next();
    NewDownloadWindow * newDownloadWindow = new NewDownloadWindow(this, query.value(0).toString());
    query.finish();

    newDownloadWindow->show();
    connect(newDownloadWindow, SIGNAL(newDownload(QString,QString,QString,int)), tableModel, SLOT(addDownload(QString,QString,QString,int)));
}

void MainWindow::removeDownload()
{
    QModelIndexList index = table->selectionModel()->selection().indexes();
    if(index.size() == 0) return;
    tableModel->removeDownload(index.at(0));
}
